package com.windward.vii.service;

import com.windward.vii.common.Constants;
import com.windward.vii.common.JsonResult;
import com.windward.vii.common.ResultCode;
import com.windward.vii.config.PlatformConfig;
import com.windward.vii.dao.entity.*;
import com.windward.vii.dao.mapper.*;
import com.windward.vii.utils.BigDecimalUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

/**
 * Created by tiansj on 2017/8/29.
 */
@Component
public class GiftService {

    private static Logger logger = LoggerFactory.getLogger(GiftService.class);

    @Autowired
    PlatformTransactionManager transactionManager;
    @Resource
    ChatMapper chatMapper;
    @Resource
    GiftMapper giftMapper;
    @Resource
    GiftRecordMapper giftRecordMapper;
    @Resource
    AssetUserAccountMapper assetUserAccountMapper;
    @Resource
    AssetUserConsumeMapper assetUserConsumeMapper;
    @Resource
    AssetUserIncomeMapper assetUserIncomeMapper;
    @Resource
    AssetPlatformProfitMapper assetPlatformProfitMapper;
    @Resource
    AssetPlatformProfitRateMapper assetPlatformProfitRateMapper;
    @Resource
    PlatformConfig platformConfig;
    @Resource
    OrganizationMapper organizationMapper;
    @Resource
    AssetPlatformAccountMapper assetPlatformAccountMapper;

    public JsonResult getGiftList() {
        JsonResult jsonResult = JsonResult.success();
        jsonResult.setBody(giftMapper.getGiftList());
        return jsonResult;
    }

    public JsonResult sendGift(Long uid, Long anchorUid, Long giftId, Integer sourceType, Long chatId) {
        if(sourceType == Constants.Gift.SOURCE_TYPE_CHAT) {
            // 检查聊天关系和状态
            Chat chat = chatMapper.selectByPrimaryKey(chatId);
            if(chat == null) {
                return new JsonResult(ResultCode.ERROR_CODE_701,"聊天关系不存在(chatId错误)，请重试");
            }
            if(!chat.getAnchorUid().equals(anchorUid) || !chat.getUid().equals(uid)) {
                return new JsonResult(ResultCode.ERROR_CODE_701,"聊天关系无法对应");
            }
            if(chat.getStatus() != Constants.Chat.STATUS_ACCEPT) {
                return new JsonResult(ResultCode.ERROR_CODE_701,"聊天状态可能已取消或终止");
            }
        }

        // 检查礼物
        Gift gift = giftMapper.selectByPrimaryKey(giftId);
        if(gift == null) {
            return JsonResult.error("礼物已下架，请刷新界面");
        }

        int price = gift.getCoin();

        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = transactionManager.getTransaction(def);
        boolean isConsumeSuccess = false;
        try {
            // 检查用户余额
            AssetUserAccount assetUserAccount = assetUserAccountMapper.selectByUidForUpdate(uid);
//            if(assetUserAccount.getAvailableRechargeCoin() + assetUserAccount.getAvailableIncomeCoin() < price) {
            if(assetUserAccount.getAvailableReceiveCoin() + assetUserAccount.getAvailableRechargeCoin() < price) {
                return new JsonResult(ResultCode.ERROR_CODE_702,"可用V钻不足，请充值");
            }

            AssetUserAccount anchorUserAccount = assetUserAccountMapper.selectByUid(anchorUid);
            // 主播/平台分成比例
            BigDecimal rate = null;
            Organization organization = null;
            if(anchorUserAccount.getOrganizationId() != null && anchorUserAccount.getOrganizationId() > 0) {
                // 查询机构分成比例
                organization = organizationMapper.selectByPrimaryKey(anchorUserAccount.getOrganizationId());
                if(organization != null) {
                    rate = organization.getProfitRate();
                }
            }
            if(rate == null) {
                // 查询平台分成比例
                AssetPlatformProfitRate assetPlatformProfitRate = assetPlatformProfitRateMapper.selectByType(Constants.AssetUserConsume.TYPE_GIFT);
                if(assetPlatformProfitRate != null) {
                    rate = assetPlatformProfitRate.getRate();
                }
            }
            if(rate == null) {
                // 系统默认设置
                rate = platformConfig.getGiftProfitRate();
            }

            // 主播分成比例
            int anchorIncome = BigDecimalUtil.mul(new BigDecimal(price), rate).intValue();
            // 平台分成比例
            int platformIncome = price - anchorIncome;

            // 扣除用户的钱
            int row = 0;
            int availableReceiveCoin = assetUserAccount.getAvailableReceiveCoin();
            if(availableReceiveCoin >= price) {
                row = assetUserAccountMapper.consumeReceiveIcon(uid, price);
            } else if(availableReceiveCoin > 0) {
                row = assetUserAccountMapper.consumeReceiveIcon(uid, availableReceiveCoin);
                if(row > 0) {
                    row = assetUserAccountMapper.consumeRechargeIcon(uid, price - availableReceiveCoin);
                }
            } else {
                row = assetUserAccountMapper.consumeRechargeIcon(uid, price);
            }
            if(row < 1) {
                return new JsonResult(ResultCode.ERROR_CODE_703,"扣除用户V钻失败，请重试");
            }

//            int row = assetUserAccountMapper.consumeRechargeIcon(uid, price);
//            if(row <= 0) {
//                return new JsonResult(ResultCode.ERROR_CODE_703,"扣除用户V钻失败，请重试");
//            }

            // 添加消费记录
            AssetUserConsume assetUserConsume = new AssetUserConsume();
            assetUserConsume.setUid(uid);
            if(assetUserAccount.getOrganizationId() != null) {
                assetUserConsume.setOrgId(assetUserAccount.getOrganizationId());
            }
            assetUserConsume.setAnchorUid(anchorUid);
            assetUserConsume.setCoin(price);
            if(chatId > 0) {
                assetUserConsume.setChatId(chatId);
            }
            assetUserConsume.setGiftId(giftId);
            assetUserConsume.setType(Constants.AssetUserConsume.TYPE_GIFT);
            assetUserConsume.setCreateTime(new Date());
            row = assetUserConsumeMapper.insertSelective(assetUserConsume);
            if(row <= 0) {
                return new JsonResult(ResultCode.ERROR_CODE_704,"生成用户消费记录失败，请重试");
            }

            // 减少消费者对应机构的钱
//            if(assetUserAccount.getOrganizationId() != null && assetUserAccount.getOrganizationId() > 0) {
//                // 扣除金额
//                if(availableRechargeCoin < price) {
//                    int orgComsumePrice = price - availableRechargeCoin;
//                    row = organizationMapper.consume(assetUserAccount.getOrganizationId(), orgComsumePrice);
//                    if(row <= 0) {
//                        return new JsonResult(ResultCode.ERROR_CODE_705,"扣除用户机构消费失败，请重试");
//                    }
//                }
//            }

            // 增加主播的钱
            row = assetUserAccountMapper.incomeCoin(anchorUid, anchorIncome);
            if(row <= 0) {
                return new JsonResult(ResultCode.ERROR_CODE_706,"增加播主收入失败，请重试");
            }
            // 增加机构的钱
            if(organization != null) {
                row = organizationMapper.income(organization.getId(), anchorIncome);
                if(row <= 0) {
                    return new JsonResult(ResultCode.ERROR_CODE_707,"增加机构收入失败，请重试");
                }
            }

            // 添加收入记录
            AssetUserIncome assetUserIncome = new AssetUserIncome();
            assetUserIncome.setUid(anchorUid);
            if(anchorUserAccount.getOrganizationId() != null) {
                assetUserIncome.setOrgId(assetUserAccount.getOrganizationId());
            }
            assetUserIncome.setConsumerUid(uid);
            assetUserIncome.setCoin(anchorIncome);
            if(chatId > 0) {
                assetUserIncome.setChatId(chatId);
            }
            assetUserIncome.setGiftId(giftId);
            assetUserIncome.setType(Constants.AssetUserConsume.TYPE_GIFT);
            assetUserIncome.setCreateTime(new Date());
            row = assetUserIncomeMapper.insertSelective(assetUserIncome);
            if(row <= 0) {
                return new JsonResult(ResultCode.ERROR_CODE_708,"生成播主收入记录，请重试");
            }

            // 添加送礼记录
            GiftRecord giftRecord = new GiftRecord();
            giftRecord.setSenderUid(uid);
            giftRecord.setReceiverUid(anchorUid);
            giftRecord.setSourceType(sourceType);
            if(chatId > 0) {
                giftRecord.setChatId(chatId);
            }
            giftRecord.setGiftId(giftId);
            giftRecord.setGiftCoin(gift.getCoin());
            giftRecord.setGiftName(gift.getName());
            giftRecord.setCreateTime(new Date());
            row = giftRecordMapper.insertSelective(giftRecord);
            if(row <= 0) {
                return new JsonResult(ResultCode.ERROR_CODE_709,"生成送礼记录失败，请重试");
            }

            // 添加平台收入记录
            AssetPlatformProfit assetPlatformProfit = new AssetPlatformProfit();
            assetPlatformProfit.setCoin((long) platformIncome);
            assetPlatformProfit.setIncomeId(assetUserIncome.getId());
            assetPlatformProfit.setRate(rate);
            assetPlatformProfit.setType(Constants.AssetUserConsume.TYPE_GIFT);
            assetPlatformProfit.setCreateTime(new Date());
            assetPlatformProfit.setAnchorUid(anchorUid);
            assetPlatformProfit.setConsumerUid(uid);
            if(chatId > 0) {
                assetPlatformProfit.setChatId(chatId);
            }
            assetPlatformProfit.setGiftId(giftId);
            row = assetPlatformProfitMapper.insertSelective(assetPlatformProfit);
            if(row <= 0) {
                return new JsonResult(ResultCode.ERROR_CODE_710,"生成平台收入记录，请重试");
            }

            // 平台运营支出
            if(availableReceiveCoin > 0) {
                int opexCoin;
                if(availableReceiveCoin > price) {
                    opexCoin = price;
                } else {
                    opexCoin = availableReceiveCoin;
                }
                row = assetPlatformAccountMapper.opex(opexCoin);
                if(row < 1) {
                    logger.error("consume: ERROR_CODE_710, 更新平台支出异常，请重试");
                    return new JsonResult(ResultCode.ERROR_CODE_710,"更新平台支出异常，请重试");
                }
            }

            isConsumeSuccess = true;
            JsonResult response = JsonResult.success();
//            response.setBody(assetUserAccount.getAvailableRechargeCoin() + assetUserAccount.getAvailableIncomeCoin() - price);
            response.setBody(assetUserAccount.getAvailableRechargeCoin() + assetUserAccount.getAvailableReceiveCoin() - price);
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.error();
        } finally {
            if(isConsumeSuccess) {
                transactionManager.commit(status);
            } else {
                transactionManager.rollback(status);
            }
        }
    }

}
